package com.org.oracle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.org.oracle.mapper.QuestionsMapper;
import com.org.oracle.mysql.entity.Questions;
import com.org.oracle.mysql.vo.QuestionAddCommentVo;
import com.org.oracle.mysql.vo.QuestionsVo;
import com.org.oracle.result.Result;
import com.org.oracle.service.QuestionCommentService;
import com.org.oracle.service.QuestionsService;
import com.org.oracle.util.BeanCopyUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;
import java.util.stream.Collectors;

/**
 * (Questions)表服务实现类
 *
 * @author luo
 * @since 2024-11-13 17:22:01
 */
@Service("questionsService")
public class QuestionsServiceImpl extends ServiceImpl<QuestionsMapper, Questions> implements QuestionsService {

    @Resource
    private QuestionCommentService questionCommentService;
    //获取所有题目
    //TODO 可以做分页查询
    @Override
    public Result getQuestion() {
        List<Questions> questionsList = convertToQuestionsList(list());
        List<QuestionsVo> questionsVos = BeanCopyUtils.copyBeanList(questionsList, QuestionsVo.class);
        return Result.ok(questionsVos);
    }
    //根据章节id获取题目(更新了增加评论)
    @Override
    public Result getQuestionByChapterId(String id) {
        LambdaQueryWrapper<Questions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Questions::getChapterId, id);
        List<Questions> questionsList = convertToQuestionsList(list(queryWrapper));
        List<QuestionAddCommentVo> questionAddCommentVos = BeanCopyUtils.copyBeanList(questionsList, QuestionAddCommentVo.class);
        List<QuestionAddCommentVo> questionAddCommentVoList = questionAddCommentVos.stream()
                .map(questionAddCommentVo ->
                        questionAddCommentVo.setQuestionCommentList(
                                questionCommentService.getCommentsByQuestionId(questionAddCommentVo.getId().toString())))
                .toList();
        return Result.ok(questionAddCommentVoList);
    }

    /**
     * 设置Question对象的options到optionsList
     * @param questions 原对象
     * @return List<Questions> 其中的对象questions的optionsList已经被正确添加
     */
    @Override
    public List<Questions> convertToQuestionsList(List<Questions> questions) {
        return questions.stream()
                .map(questions1 -> {
                    try {
                        return questions1.setOptionsList(convertOptionsToList(questions1.getOptions()));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());
    }

    /**
     * 根据题目id列表获取响应的答案
     * @param questionIds 题目id列表
     * @return answerMap==> Map，键为题目ID，值为正确答案
     */
    @Override
    public Map<Long, String> getAnswersByIds(List<Long> questionIds) {
        LambdaQueryWrapper<Questions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Questions::getId,questionIds);
        List<Questions> questions = list(queryWrapper);
        //创建Map，键为题目ID，值为正确答案
        Map<Long,String> answerMap = new HashMap<>();
        for(Questions question:questions){
            answerMap.put(question.getId(),question.getAnswer());
        }
        return answerMap;
    }

    /**
     *
     * @param questionId 题目id
     * @return 该题的答案
     */
    @Override
    public String getAnswerById(Long questionId) {
        Questions question = getById(questionId);
        return question!= null? question.getAnswer() : null;
    }

    /**
     * 将Question对象的options 字符串转换为 List<String>
     * @param options options原来是存储题目的选项的{"A": "数据存储", "B": "计算机网络", "C": "操作系统", "D": "数据库"}
     * @return "optionsList": [
     *                 "A.数据存储",
     *                 "B.计算机网络",
     *                 "C.操作系统",
     *                 "D.数据库"
     *             ]
     * @throws Exception readValue方法有异常需抛出
     */
    private List<String> convertOptionsToList(String options) throws Exception {
        //检查 options 不为 null 且不为空
        Preconditions.checkArgument(options != null && !options.isEmpty(), "Options string must not be null or empty");

        // 使用 Jackson 将 JSON 字符串转换为 Map
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> map = objectMapper.readValue(options, new TypeReference<>() {});

        // 创建一个列表，用于存储格式化后的选项
        List<String> optionsList = new ArrayList<>();

        // 遍历 map，根据键值对生成符合格式的选项
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String formattedOption = entry.getKey() + "." + entry.getValue(); // 格式化为 "A.数据存储"
            optionsList.add(formattedOption);
        }
        return optionsList;
    }

    //根据章节ID获取题目数
    @Override
    public Integer getQuestionNumByChapterId(String ChapterId) {
        LambdaQueryWrapper<Questions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Questions::getChapterId,ChapterId);
        long count = count(queryWrapper);
        return Math.toIntExact(count);
    }

    private List<Questions> getQuestionsByChapterId(String id) {
        LambdaQueryWrapper<Questions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Questions::getChapterId, id);
        return list(queryWrapper);
    }

    /**
     * 批量保存问题
     * @param questions 问题对象列表
     */
    @Override
    @Transactional
    public void saveQuestions(List<Questions> questions) {
        if(questions != null && !questions.isEmpty()){
            this.saveBatch(questions);
        }
    }
}
